<template>
  <a-modal
    title="报表配置"
    v-model:visible="visible"
    :ok-loading="confirmLoading"
    :mask-closable="false"
    unmount-on-close
    ok-text="确认"
    :width="1200"
    @ok="handleOk"
    @cancel="close"
    :body-style="{'max-height': '700px','overflow':'auto'}"
  >
    <div style="display:flex;align-items: center;height:45px">
      <a-radio-group v-model="exhibitType">
        <a-radio value="table">
          列表
        </a-radio>
        <a-radio value="card">
          卡片
        </a-radio>
      </a-radio-group>
      <div v-if="exhibitType==='card'" style="padding: 0px 6px;display:flex;align-items: center">
        <div>行/卡片：</div>
        <a-input-number id="inputNumber" v-model="lines" :min="1" :max="999" />
      </div>
    </div>
    <a-divider />
    <!-- <variable-selection :var-options="nameList" v-if="visible && varVisible"></variable-selection> -->
    <a-spin :spinning="confirmLoading">
      <a-form
        ref="form"
        :model="form"
        :rules="rules"
        @submit="handleOk"
        @submit.native.prevent>
        <draggable
          v-model="form.dataSourceExpandAddDTOList"
          handle=".drag-handle">
          <div v-for="(domain,index) in form.dataSourceExpandAddDTOList" :key="index">
            <a-row
              type="flex"
              :gutter="16"
              justify="space-between"
              align="middle"
            >
              <!-- 添加拖拽图标 -->
              <a-col :md="1" :sm="1">
                <icon-drag-dot-vertical class="drag-handle" style="cursor: move;" />
              </a-col>

              <a-col :md="6" :sm="6" v-if="domain.type !== 'variable'">
                <a-form-item label="显示名" :field="`dataSourceExpandAddDTOList.${index}.columnName`" :rules="rules.columnName">
                  <a-input v-model="domain.columnName"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="6" v-else>
                <a-form-item label="显示名" :field="`dataSourceExpandAddDTOList.${index}.columnAs`" :rules="rules.columnAs">
                  <a-input v-model="domain.columnAs"></a-input>
                </a-form-item>
              </a-col>

              <a-col :md="6" :sm="8" v-if="domain.type !== 'variable'" >
                <a-form-item label="公式" :field="`dataSourceExpandAddDTOList.${index}.columnEl`" :rules="rules.columnEl">
                  <a-input v-model="domain.columnEl"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="8" v-else>
                <a-form-item label="字段名" :field="`dataSourceExpandAddDTOList.${index}.columnName`" :rules="rules.columnName">
                  <a-input v-model="domain.columnName" :disabled="true"></a-input>
                </a-form-item>
              </a-col>

              <a-col :md="4" :sm="4">
                <a-form-item label="类型" :field="`dataSourceExpandAddDTOList.${index}.columnType`" :rules="rules.columnType">
                  <a-select v-model="domain.columnType" default-value="default">
                    <a-option value="default">
                      默认
                    </a-option>
                    <a-option value="rate">
                      百分比
                    </a-option>
                    <a-option value="YYYY">年</a-option>
                    <a-option value="YYYY-MM">年/月</a-option>
                    <a-option value="YYYY-MM-DD">年/月/日</a-option>
                    <a-option value="YYYY-MM-DD HH:mm:ss">年/月/日 时分秒</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="1" :sm="1">
                <a-form-item label="分组">
                  <!-- {{domain}} -->
                  <a-checkbox :checked="domain.group" @change="onChange(domain,$event)"></a-checkbox>
                </a-form-item>
              </a-col>
              <a-col :md="1" :sm="1">
                <a-form-item label="合计">
                  <a-radio :value="domain.type !== 'variable'?domain.columnName:domain.columnAs"></a-radio>
                </a-form-item>
              </a-col>
              <a-col :md="1" :sm="1" style="margin-top: 12px">
                <a-badge v-if="domain.status" status="success" />
              </a-col>
              <!-- <a-badge v-if="domain.status" status="success" /> -->
              <a-col :md="1" :sm="1" style="margin-top: 12px">
                <a-button
                  v-if="form.dataSourceExpandAddDTOList.length > 0"
                  type="text"
                  :disabled="form.dataSourceExpandAddDTOList.length === 1"
                  @click="removeDomain(domain)"
                >
                  <icon-minus-circle />
                </a-button>
              </a-col>
            </a-row>
          </div>
        </draggable>
        <a-form-item>
          <a-button type="dashed" @click="addDomain"><icon-plus style="margin-right: 6px" />添加公式</a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
import VariableSelection from '@/components/Custom/VariableSelection.vue'
import _ from 'lodash'
import draggable from 'vuedraggable'

export default {
  components: {
    VariableSelection,
    draggable
  },
  inject: ['dataObj'],
  computed: {
    form () {
      if (this.current) {
        return this.dataObj.buttonData[this.current] || {}
      } else {
        return {}
      }
    },
    nameList () {
      return this.dataShowFieldOptions.map(item => {
        // if (item.function) {
        //   return { label: item.columnAs, value: item.columnAs, isExpression: true }
        // } else {
          return { label: item.columnAs, value: item.columnAs || item.columnKey, isExpression: true }
        // }
      })
    }
  },
  watch: {
    visible (newVal) {
      setTimeout(() => {
        this.varVisible = newVal // 给变量按钮一个缓冲显示的时间
      }, 400)
    }
  },
  data () {
    return {
      varVisible: false,
      visible: false,
      total: undefined,
      exhibitType: 'table',
      lines: undefined,
      confirmLoading: false,
      dataShowFieldOptions: [], // 数据源展示字段
      rawdataSourceExpandAddDTOList: [], // 保存原始数据
      rules: {
        columnName: [{ required: true, message: '必填' }],
        columnEl: [{ required: true, message: '必填' }],
        columnAs: [{ required: true, message: '必填' }],
        columnType: [{ required: true, message: '必填' }]
      },
      current: null, // 选择buttonData下标
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 }
        }
      },
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 24, offset: 0 },
          sm: { span: 20, offset: 4 }
        }
      }
    }
  },
  methods: {
    onChange (value, e) {
      // 选择分组
      this.$set(value, 'group', !value.group)
    },
    addDomain () {
      this.form.dataSourceExpandAddDTOList.push({
        columnName: '',
        columnAs: '',
        columnEl: '',
        group: false,
        type: 'el',
        columnType: 'default'
      })
    },
    removeDomain (item) {
      const index = this.form.dataSourceExpandAddDTOList.indexOf(item)
      if (index !== -1) {
        this.form.dataSourceExpandAddDTOList.splice(index, 1)
      }
    },
    handleOk () {
      try {
        this.$refs.form.validate(async valid => {
          if (valid) {
            const { tableButtonReqDTOList } = this.dataObj.tableDesc
            this.form.tableButtonAddDTO.buttonStyle = JSON.stringify({
              exhibitType: this.exhibitType,
              lines: this.lines,
              total: this.total
            })
            console.log(this.form.tableButtonAddDTO.buttonStyle, 'this.form.tableButtonAddDTO.buttonStyle')
            const tableButton = tableButtonReqDTOList?.find(c => c.tableButtonAddDTO.buttonName === this.form.tableButtonAddDTO.buttonName)
            const { buttonEventAddDTO: { foreignId: dataId } } = this.form
            // 在发送前更新排序权重
            this.form.dataSourceExpandAddDTOList.forEach((item, index) => {
              item.index = index + 1
              if (tableButton) {
                const { tableButtonAddDTO: { buttonId } } = tableButton
                item.buttonId = buttonId
              }
              item.dataId = dataId
            })

            this.visible = false
          }
        })
      } catch (e) {
        console.error('执行错误', e)
      } finally {
        this.confirmLoading = false
      }
    },
    async open (current) {
      this.visible = true
      this.current = current // 获取下标
      this.rawdataSourceExpandAddDTOList = _.cloneDeep(this.dataObj.buttonData[this.current].dataSourceExpandAddDTOList)
      const { buttonEventAddDTO: { foreignId: dataId } } = this.dataObj.buttonData[this.current]
      const buttonStyle = this.dataObj.buttonData[this.current].tableButtonAddDTO.buttonStyle
      if (buttonStyle) {
        console.log(buttonStyle, 'buttonStylebuttonStyle', JSON.parse(buttonStyle))
        const { exhibitType, lines, total } = JSON.parse(buttonStyle)
        this.exhibitType = exhibitType
        this.lines = lines
        this.total = total
      }
      await this.queryDataSourceDetails(dataId, false)
    },
    close () {
      this.dataObj.buttonData[this.current].dataSourceExpandAddDTOList = this.rawdataSourceExpandAddDTOList
      this.visible = false
    },
    // 选择了数据源，需要查询有哪些展示字段
    async queryDataSourceDetails (dataId, isRest = true) {
      try {
        if (!dataId) return
        if (isRest) {
          Object.assign(this.dataObj.buttonData[this.current]?.dataSourceExpandAddDTOList, {})
        }

        this.status = null
        const result = await this.$http.get('/datasource/queryDataSourceDetail', {
          params: {
            dataId
          }
        })
        const { data } = result
        const { dataColumnQueryDTOList, aggregateFunctionInfoReqDTO } = data
        const { aggregateFunctionInfoAddDTOList } = aggregateFunctionInfoReqDTO || {}
        // 需要根据columnKey去重后的对象数组，而不是单纯的columnKey集合，可以进一步处理：
        this.dataShowFieldOptions = dataColumnQueryDTOList.concat(aggregateFunctionInfoAddDTOList || [])
        // 新增的时候不管
        if (this.form.dataSourceExpandAddDTOList?.length === 0 || this.form.dataSourceExpandAddDTOList?.[0].dataId !== dataId) { // 新增的时候加上变量
          console.log('新增')
          this.form.dataSourceExpandAddDTOList = this.dataShowFieldOptions.map((item, index) => {
            return (
              {
                columnName: item.columnAs, // 名字不一样
                columnAs: item.columnAs,
                columnEl: '',
                type: 'variable',
                group: item.group,
                dataId: item.dataId,
                index: index + 1,
                columnType: 'default'
              }
            )
          })
        } else {
          // const formAsList = this.form.dataSourceExpandAddDTOList.map((uiItem, index) => { return uiItem.columnAs })
          console.log('编辑')
          const formAsList = this.form.dataSourceExpandAddDTOList.map((uiItem, index) => { return uiItem.columnName })
          this.form.dataSourceExpandAddDTOList.map((uiItem, index) => {
            this.dataShowFieldOptions.map((item, index) => {
              if (uiItem.columnName === item.columnAs) { // 一样的就改 columnName
                uiItem.dataId = item.dataId
                uiItem.columnName = item.columnAs
                uiItem.columnEl = ''
                uiItem.type = 'variable'
              } else {
                if (!formAsList.includes(item.columnAs)) { // 新变量得往里面添加
                  this.form.dataSourceExpandAddDTOList.push(
                    {
                      columnName: item.columnAs, // 名字不一样
                      columnAs: item.columnAs,
                      columnEl: '',
                      type: 'variable',
                      group: item.group,
                      dataId: item.dataId,
                      index: index + 1,
                      columnType: 'default',
                      status: true // 新的加表示
                    }
                  )
                  formAsList.push(item.columnAs)
                }
              }
            })
          })
        }
      } catch (e) {
        console.error('失败', e)
      }
    }
  }
}
</script>
<style lang="less" scoped>
.drag-handle {
  padding: 10px;
  color: #999;
  &:hover {
    color: #1890ff;
  }
}
</style>
